<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="买家" prop="buyerName">
        <el-input
          v-model="queryParams.buyerName"
          placeholder="请输入买家名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="params.goodsId">
        <el-input v-model="queryParams.params.goodsId" placeholder="请输入商品编码" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="params.goodsName">
        <el-input v-model="queryParams.params.goodsName" placeholder="请输入商品名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="IMEI" prop="params.goodsSn">
        <el-input v-model="queryParams.params.goodsSn" placeholder="请输入IMEI" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="销售时间" prop="buyTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.buyTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择购销售时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="销售时间">
        <el-date-picker
          size="small"
          v-model="buyTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="buyTimeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="销售金额" prop="salePrice">
        <el-input
          v-model="queryParams.salePrice"
          placeholder="请输入销售金额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售人" prop="saleUserName">
        <el-input
          v-model="queryParams.saleUserName"
          placeholder="请输入销售人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="payMethod">
        <el-select v-model="queryParams.payMethod" placeholder="请选择支付方式" clearable size="small" @keyup.enter.native="handleQuery">
          <el-option v-for="item in payMethodOptions" :value="item.v" :label="item.l" />
        </el-select>
      </el-form-item>
      <el-form-item label="收款账户" prop="payAccount">
        <el-select v-model="queryParams.payAccount" placeholder="请选择收款账户" clearable size="small" @keyup.enter.native="handleQuery">
          <el-option v-for="item in billPayeeOptions" :value="item.dictValue" :label="item.dictLabel" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="item in statusOptions" :label="item.l" :value="item.v" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核人" prop="checkUserName">
        <el-input
          v-model="queryParams.checkUserName"
          placeholder="请输入审核人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sale:bill:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="dataOpen = !dataOpen"
          v-hasPermi="['sale:bill:listData']"
        >{{dataOpen ? '隐藏' : '统计'}}</el-button>
      </el-col>
      <el-col :span="16">
        <div v-if="dataOpen && dataMap">
          <el-tag style="margin-right: 10px">成本：{{dataMap.cost}}</el-tag>
          <el-tag style="margin-right: 10px">运费：{{dataMap.yf}}</el-tag>
          <el-tag style="margin-right: 10px">配件：{{dataMap.parts}}</el-tag>
          <el-tag style="margin-right: 10px">销售：{{dataMap.sale}}</el-tag>
          <el-tag style="margin-right: 10px">利润：{{dataMap.lr}}</el-tag>
        </div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="billList" :row-class-name="tableRowClassName">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="买家" align="center" prop="buyerName" v-has-permi="['sale:bill:buyer']" />
      <el-table-column label="购买时间" align="center" prop="buyTime" width="150" />
      <el-table-column label="销售金额" align="center" prop="salePrice" />
      <el-table-column label="总成本" align="center" prop="costPrice" />
      <el-table-column label="运费" align="center" prop="freight" />
      <el-table-column label="配件成本" align="center" prop="accCostPrice" />
      <el-table-column label="利润" align="center" prop="profitPrice" />
      <el-table-column label="销售人" align="center" prop="saleUserName" />
      <el-table-column label="支付方式" align="center" prop="payMethod">
        <template v-slot="scope">
          <el-tag v-for="item in payMethodOptions" :type="item.t" v-if="item.v === scope.row.payMethod">{{item.l}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收款账户" align="center" prop="payAccount" :formatter="formatterPayee" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag v-for="item in statusOptions" :type="item.t" v-if="item.v === scope.row.status">{{item.l}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="checkUserName" />
      <el-table-column label="审核时间" align="center" prop="checkTime" width="180" />
      <el-table-column label="是否有退货" align="center" prop="refundNum">
        <template v-slot="scope">
          <el-tag v-if="scope.row.refundNum > 0" type="warning">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="text" v-if="checkImport(scope.row)" @click="gotoSaleFrom(scope.row)">导入出售单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :visible.sync="open" title="账单详情" width="60%" append-to-body @close="detailClose">
      <el-form label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="买家：">{{form.buyerName}}</el-form-item>
            <el-form-item label="利润：">{{form.profitPrice}}元</el-form-item>
            <el-form-item label="运费：">{{form.freight}}元</el-form-item>
            <el-form-item label="备注：">{{form.remark}}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售人：">{{form.saleUserName}}</el-form-item>
            <el-form-item label="总成本：">{{form.costPrice}}元</el-form-item>
            <el-form-item label="配件成本：">{{form.accCostPrice}}元</el-form-item>
            <el-form-item label="快递单号：">{{form.trackingNumber}}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售时间：">{{form.buyTime}}</el-form-item>
            <el-form-item label="销售金额：">{{form.salePrice}}元</el-form-item>
            <el-form-item label="支付方式：">
              <el-tag v-for="item in payMethodOptions" :type="item.t" v-if="item.v === form.payMethod">{{item.l}}</el-tag>
            </el-form-item>
            <el-form-item label="收款账户：">
              {{formatterPayee(this.form)}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="支付凭证：">
              <el-image :src="form.imgUrl" style="width: 146px;height: 146px;border-radius: 5px;" fit="cover" :preview-src-list="[form.imgUrl]" :z-index="999999" />
            </el-form-item>
            <el-form-item label="审核备注：" v-if="form.checkRemark">{{form.checkRemark}}</el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-tabs v-model="activeName">
        <el-tab-pane label="商品列表" name="goods">
          <el-table :data="form.goodsList" border max-height="350px">
            <el-table-column label="商品编码" align="center" prop="goodsId" width="180" />
            <el-table-column label="商品名称" align="center" prop="goodsName" show-overflow-tooltip />
            <el-table-column label="IMEI" align="center" prop="goodsSn" show-overflow-tooltip />
            <el-table-column label="规格" align="center" prop="specs" show-overflow-tooltip />
            <el-table-column label="验机报告" align="center" prop="testInfo" show-overflow-tooltip />
            <el-table-column label="成本价格" align="center" prop="costPrice" />
            <el-table-column label="销售金额" align="center" prop="salePrice" />
            <el-table-column label="配件金额" align="center">
              <template v-slot="scope">
                {{getPartsPrice(scope.row)}}
              </template>
            </el-table-column>
            <el-table-column label="是否退货" align="center">
              <template v-slot="scope">
                <el-tag v-if="scope.row.hasRefund === 0" type="info">否</el-tag>
                <el-tag v-if="scope.row.hasRefund === 1" type="warning">是</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button type="text" v-if="form.status === 2 && scope.row.hasRefund === 0" @click="handleRefund(scope.row)">退 货</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="配件列表" name="parts">
          <el-table border :data="form.partsList" max-height="350px" >
            <el-table-column label="商品编码" align="center" prop="goodsId" />
            <el-table-column label="商品名称" align="center" show-overflow-tooltip>
              <template v-slot="scope">
                {{getGoodsName(scope.row)}}
              </template>
            </el-table-column>
            <el-table-column label="配件名称" align="center" prop="partsName" />
            <el-table-column label="配件单价" align="center" prop="partsPrice" />
            <el-table-column label="配件数量" align="center" prop="partsNumber" />
            <el-table-column label="总金额" align="center" prop="price" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div style="margin-top: 5px" v-if="form.status === 1">
        <el-input v-model="form.checkRemark" placeholder="审核备注（作废请备注作废原因）" />
      </div>

      <div slot="footer" class="dialog-footer" v-if="form.status === 1">
        <el-button type="success" plain @click="handlePass()" size="small">通 过</el-button>
        <el-button type="danger" plain @click="handleNoPass()" size="small">作 废</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="refundOpen" :title="title" width="500px" append-to-body>
      <el-form ref="refundForm" :model="refundForm" :rules="rules" label-width="80px">
        <el-form-item label="退回金额" prop="refundPrice">
          <el-input-number v-model="refundForm.refundPrice" placeholder="请输入退回金额" />
        </el-form-item>
        <el-form-item label="付款方式" prop="payMethod">
          <el-select v-model="refundForm.payMethod" placeholder="请选择付款方式" filterable>
            <el-option v-for="item in payMethodOptions" :label="item.l" :value="item.v" />
          </el-select>
        </el-form-item>
        <el-form-item label="付款账户" prop="payAccount">
          <el-select v-model="refundForm.payAccount" placeholder="请选择付款账户" filterable>
            <el-option v-for="item in billPayeeOptions" :value="item.dictValue" :label="item.dictLabel" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="refundForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listBill, exportBill, getBill, updateBillNoPass, updateBillPass, listBillData} from "@/api/sale/bill";
import {getDicts} from "@/api/system/dict/data";
import {addRefund} from "@/api/sale/refund";

export default {
  name: "Bill",
  components: {
  },
  data() {
    return {
      buyTimeRange: [],
      dataOpen: false,
      dataMap: undefined,
      detailId: this.$route.query.detailId,
      refundForm: {},
      refundOpen: false,
      activeName: 'goods',
      payMethodOptions: [
        {v:'alipay', l:'支付宝', t: ""},
        {v: 'wechat', l:'微信', t: "success"},
        {v: 'cash', l:'现金', t: "danger"},
        {v: 'bank', l:'银行卡', t: "warning"},
        {v: 'other', l:'其它', t: "info"}
      ],
      //账户类型
      billPayeeOptions: [],
      //1=待审核，2=通过，3=作废
      statusOptions: [
        {v:1, l:'待审核', t: '' },
        {v:2, l:'通过', t: 'success' },
        {v:3, l:'作废', t: 'info' }
      ],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 版本3 --- 账单主表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        buyerName: null,
        salePrice: null,
        saleUserName: null,
        payMethod: null,
        payAccount: null,
        status: null,
        checkUserName: null,
        buyTime: undefined,
        params: {
          goodsId: '',
          goodsName: '',
          goodsSn: ''
        }
      },
      // 表单参数
      form: {
        checkRemark: undefined
      },
      // 表单校验
      rules: {
        payMethod: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        payAccount: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        refundPrice: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    getDicts("recovery_bill_payee").then(res => {
      this.billPayeeOptions = res.data;
    })
    if(this.detailId) {
      this.handleDetail({id: this.detailId});
    }
  },
  methods: {
    buyTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams, 'buyStartTime');
        this.$delete(this.queryParams, 'buyEndTime');
        return
      }
      this.$set(this.queryParams, 'buyStartTime', e[0]);
      this.$set(this.queryParams, 'buyEndTime', e[1]);
    },
    tableRowClassName({row, rowIndex}) {
      if(row.profitPrice < 0)
        return 'danger-row';
      return '';
    },
    getGoodsName(row) {
      for(let i = 0; i < this.form.goodsList.length; i++) {
        if(this.form.goodsList[i].goodsId === row.goodsId)
          return this.form.goodsList[i].goodsName;
      }
      return "";
    },
    getPartsPrice(row) {
      let res =0;
      this.form.partsList.forEach(item => {
        if(row.goodsId === item.goodsId)
          res += Number(item.price)
      })
      return res;
    },
    detailClose() {
      if (this.detailId) {
        this.$router.go(-1);
        this.$store.dispatch("tagsView/delView", this.$route)
      }
    },
    // 取消按钮
    cancel() {
      this.refundOpen = false;
      this.resetRefund();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["refundForm"].validate(valid => {
        if (valid) {
          addRefund(this.refundForm).then(response => {
            this.msgSuccess("新增成功");
            this.refundOpen = false;
            this.getList();
            this.handleDetail(this.form);
          });
        }
      });
    },
    handleRefund(row) {
      this.resetRefund();
      this.refundOpen = true;
      this.title = row.goodsId + " 退货单"
      this.refundForm.saleGoodsId = row.id;
      this.refundForm.refundPrice = row.salePrice;
    },
    //退单表单重置
    resetRefund() {
      this.refundForm = {
        refundPrice : 0,
        payMethod: undefined,
        payAccount: undefined,
        saleGoodsId: undefined,
        remark: undefined
      }
    },
    gotoSaleFrom(row) {
      this.$confirm("如果您已经导入过了，并且提交出售单，请忽略本操作！", '警告', {
        confirmButtonText: "导入",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$router.push({
          path: '/sale/saleGoodsForm',
          query: {billId: row.id}
        })
      })
    },
    //导入有效期验证
    checkImport(row) {
      if(row.status === 3) {
        let checkTime = new Date(row.checkTime).getTime();
        let nowTime = new Date().getTime();
        let twoHour = 1000 * 60 * 60 * 2;
        if((nowTime - checkTime) <= twoHour)
          return true
      }
      return false;
    },
    //详情查看
    handleDetail(row) {
      getBill(row.id).then(res => {
        this.form = res.data;
        this.open = true;
      })
    },
    formatterPayee(row) {
      for (let i =0; i < this.billPayeeOptions.length; i++) {
        if(row.payAccount === this.billPayeeOptions[i].dictValue)
          return this.billPayeeOptions[i].dictLabel;
      }
      return "";
    },
    /** 查询版本3 --- 账单主列表 */
    getList() {
      this.loading = true;
      listBill(this.queryParams).then(response => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listBillData(this.queryParams).then(res => {
        this.dataMap = res.data;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.buyTimeRange = [];
      this.buyTimeChange(null);
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有账单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBill(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    //审核不通过
    handleNoPass() {
      this.$confirm("请确定发起人能在两小时内，重新发起账单在作废账单！", '警告', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateBillNoPass(this.form.id, this.form.checkRemark).then(res => {
          this.open = false;
          this.getList();
          this.msgSuccess("操作成功");
        })
      })
    },
    handlePass() {
      this.$confirm("确定通过审核吗?", '警告', {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateBillPass(this.form.id, this.form.checkRemark).then(res => {
          this.open = false;
          this.getList();
          this.msgSuccess("操作成功");
        })
      })
    }
  }
};
</script>

<style>
.el-table .danger-row {
  color: red;
  background-color: rgb(253, 226, 226);
}
</style>
